import { createSlice } from "@reduxjs/toolkit";
import tokenMgr from "../../cookieMgr/tokenMgr";
import userInfoMgr from "../../cookieMgr/userInfoMgr";
import loginApi from "../../../apis/loginApi";
import { message } from "antd";

const authSlice = createSlice({
  name: "auth",
  initialState: {
    token: tokenMgr.getToken() || "",
    userInfo: userInfoMgr.getUserInfo() || {},
  },
  reducers: {
    setToken: (state, action) => {
      state.token = action.payload;
      tokenMgr.setToken(state.token);
    },
    setUserInfo: (state, action) => {
      state.userInfo = action.payload;
      userInfoMgr.setUserInfo(state.userInfo);
    },
  },
});

const { setToken, setUserInfo } = authSlice.actions;

// 登录根据账号
const loginByAccount = (data) => {
  return async (dispatch) => {
    const res = await loginApi.administratorLoginByAccount(data);
    if (res.status >= 0) {
      dispatch(setToken(res.data));
      message.success(res.message || "登录成功");
      return true;
    } else {
      message.error(res.message || "登录成功");
      return false;
    }
  };
};

// 登录根据电话号码
const loginByPhone = (data) => {
  return async (dispatch) => {
    const res = await loginApi.administratorLoginByPhone(data);
    if (res.status >= 0) {
      dispatch(setToken(res.data));
      message.success(res.message || "登录成功");
      return true;
    } else {
      message.error(res.message || "登录成功");
      return false;
    }
  };
};

// 登出
const loginOut = () => {
  return (dispatch) => {
    dispatch(setToken(null));
  };
};

// 检查登录
const checkLogin = () => {
  return async (dispath) => {
    const res = await loginApi.checkAdministratorLogin();
    if (res.status >= 0) {
      dispath(setUserInfo(res.data));
      return true;
    } else if (res.status != null) {
      message.error(res.message || "未登录或登录已过期");
      location.href = "/login";
      return false;
    } else {
      location.href = "/login";
      return false;
    }
  };
};

export default authSlice;
export { loginByAccount, loginByPhone, loginOut, checkLogin };
